// Copyright (c) 2012-2013, yuno. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
package sugarmintcandy.widgetwindow;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.FrameLayout;

public class WindowInfo {
    public int appWidgetId;
    public int hostId;
    public int windowX;
    public int windowY;
    public int windowWidth;
    public int windowHeight;
    public int windowColor;
    public int iconX;
    public int iconY;
    public boolean iconified;
    public boolean titleBarVisible;
    public int titleBarColor;
    public String titleBarText;
    public int zOrder;
    public int workspace;
    public Anchor anchor;

    public AppWidgetProviderInfo providerInfo;

    public void init(MainDatabase db, int appWidgetId) {
	this.appWidgetId = appWidgetId;
	this.hostId = db.getHostIdFromAppWidgetId(appWidgetId);
	Context context = db.getContext();
	DisplayMetrics dm = Utilities.getDisplayMetrics(context);
	SharedPreferences preferences = PreferenceManager
		.getDefaultSharedPreferences(context);
	anchor = Anchor.valueOf(preferences.getString(PreferenceKeys.ANCHOR,
		null));
	providerInfo = AppWidgetManager.getInstance(context).getAppWidgetInfo(
		appWidgetId);
	Point p = computeInitialSize(context, dm, providerInfo);
	windowWidth = p.x;
	windowHeight = p.y;
	int left = (dm.widthPixels - p.x) / 2;
	int top = (dm.heightPixels - p.y) / 2;
	int right = left + windowWidth;
	int bottom = top + windowHeight;
	p = anchor.encodePoint(dm, left, top, right, bottom);
	windowX = p.x;
	windowY = p.y;
	iconX = Integer.MIN_VALUE;
	iconY = Integer.MIN_VALUE;
	iconified = false;
	titleBarVisible = true;
	titleBarText = null;
	if (preferences.getBoolean(PreferenceKeys.DEFAULT_COLOR_RANDOM, false)) {
	    int color = Utilities.randomColor(db);
	    color |= 0xff000000;
	    titleBarColor = color;
	    windowColor = color & 0x80ffffff;
	    db.addRecentColor(color);
	} else {
	    titleBarColor = preferences.getInt(
		    PreferenceKeys.DEFAULT_TITLE_BAR_COLOR, 0);
	    windowColor = preferences.getInt(
		    PreferenceKeys.DEFAULT_WINDOW_COLOR, 0);
	}
	zOrder = db.getMaxZOrder() + 1;
	workspace = 1 << preferences
		.getInt(PreferenceKeys.CURRENT_WORKSPACE, 0);
    }

    public void resetPosition(MainDatabase db) {
	Context context = db.getContext();
	DisplayMetrics dm = Utilities.getDisplayMetrics(context);
	SharedPreferences preferences = PreferenceManager
		.getDefaultSharedPreferences(context);
	anchor = Anchor.valueOf(preferences.getString(PreferenceKeys.ANCHOR,
		null));
	Point p = computeInitialSize(context, dm, providerInfo);
	windowWidth = p.x;
	windowHeight = p.y;
	int left = (dm.widthPixels - p.x) / 2;
	int top = (dm.heightPixels - p.y) / 2;
	int right = left + windowWidth;
	int bottom = top + windowHeight;
	p = anchor.encodePoint(dm, left, top, right, bottom);
	windowX = p.x;
	windowY = p.y;
	iconX = Integer.MIN_VALUE;
	iconY = Integer.MIN_VALUE;
	iconified = false;
	titleBarVisible = true;
    }

    public void load(Context context, Cursor c) {
	appWidgetId = getInt(c, "c_app_widget_id");
	hostId = getInt(c, "c_host_id");
	windowX = getInt(c, "c_window_x");
	windowY = getInt(c, "c_window_y");
	windowWidth = getInt(c, "c_window_width");
	windowHeight = getInt(c, "c_window_height");
	windowColor = getInt(c, "c_window_color");
	iconX = getInt(c, "c_icon_x");
	iconY = getInt(c, "c_icon_y");
	iconified = getInt(c, "c_iconified") != 0;
	titleBarVisible = getInt(c, "c_title_bar_visible") != 0;
	titleBarColor = getInt(c, "c_title_bar_color");
	titleBarText = getString(c, "c_title_bar_text");
	zOrder = getInt(c, "c_z_order");
	workspace = getInt(c, "c_workspace");
	anchor = Anchor.valueOf(getString(c, "c_anchor"));
	providerInfo = AppWidgetManager.getInstance(context).getAppWidgetInfo(
		appWidgetId);
    }

    public ContentValues save() {
	ContentValues values = new ContentValues();
	values.put("c_app_widget_id", appWidgetId);
	values.put("c_host_id", hostId);
	values.put("c_window_x", windowX);
	values.put("c_window_y", windowY);
	values.put("c_window_width", windowWidth);
	values.put("c_window_height", windowHeight);
	values.put("c_window_color", windowColor);
	values.put("c_icon_x", iconX);
	values.put("c_icon_y", iconY);
	values.put("c_iconified", iconified ? 1 : 0);
	values.put("c_title_bar_visible", titleBarVisible ? 1 : 0);
	values.put("c_title_bar_color", titleBarColor);
	values.put("c_title_bar_text", titleBarText);
	values.put("c_z_order", zOrder);
	values.put("c_workspace", workspace);
	values.put("c_anchor", anchor.name());
	return values;
    }

    private static int getInt(Cursor c, String name) {
	return c.getInt(c.getColumnIndexOrThrow(name));
    }

    private static String getString(Cursor c, String name) {
	return c.getString(c.getColumnIndexOrThrow(name));
    }

    public Drawable loadIcon(Context context) {
	try {
	    String packageName = providerInfo.provider.getPackageName();
	    Context packageContext = context.createPackageContext(packageName,
		    0);
	    if (providerInfo.icon != 0) {
		Drawable icon = packageContext.getResources().getDrawable(
			providerInfo.icon);
		if (icon != null) {
		    return icon;
		}
	    }
	    Drawable icon = context.getPackageManager().getApplicationIcon(
		    packageName);
	    if (icon != null) {
		return icon;
	    }
	} catch (Throwable ex) {
	    Debug.warn(ex);
	}
	return context.getResources().getDrawable(
		android.R.drawable.ic_menu_help);
    }

    public String getTitleBarText() {
	if (titleBarText != null) {
	    return titleBarText;
	}
	if (providerInfo != null) {
	    return providerInfo.label;
	}
	return null;
    }

    private static Point computeInitialSize(Context context, DisplayMetrics dm,
	    AppWidgetProviderInfo providerInfo) {
	int w = 0;
	int h = 0;
	if (providerInfo != null) {
	    w = providerInfo.minWidth;
	    h = providerInfo.minHeight;
	    if (providerInfo.initialLayout != 0) {
		try {
		    Context packageContext = context.createPackageContext(
			    providerInfo.provider.getPackageName(), 0);
		    LayoutInflater inflater = LayoutInflater
			    .from(packageContext);
		    View view = inflater.inflate(providerInfo.initialLayout,
			    new FrameLayout(context), false);
		    view.measure(MeasureSpec.makeMeasureSpec(0,
			    MeasureSpec.UNSPECIFIED), MeasureSpec
			    .makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		    int mw = view.getMeasuredWidth();
		    int mh = view.getMeasuredHeight();
		    if (w < mw) {
			w = mw;
		    }
		    if (h < mh) {
			h = mh;
		    }
		} catch (Throwable ex) {
		    // ignore
		}
	    }
	    Rect padding = ApiHelper.getDefaultPaddingForWidget(context,
		    providerInfo.provider, null);
	    w += padding.left + padding.right;
	    h += padding.top + padding.bottom;
	}
	int maximumWidth = dm.widthPixels - 1;
	int maximumHeight = dm.heightPixels - Math.round(16 * dm.density);
	int minimumWidth = context.getResources().getDimensionPixelSize(
		R.dimen.minimum_width);
	int minimumHeight = context.getResources().getDimensionPixelSize(
		R.dimen.minimum_height);
	if (w > maximumWidth) {
	    w = maximumWidth;
	}
	if (h > maximumHeight) {
	    h = maximumHeight;
	}
	if (w < minimumWidth) {
	    w = minimumWidth;
	}
	if (h < minimumHeight) {
	    h = minimumHeight;
	}
	return new Point(w, h);
    }
}
